package sv.edu.edutec.fotos.servlet;

import java.security.Principal;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sun.security.auth.UserPrincipal;


import sv.edu.edutec.fotos.model.TblComment;
import sv.edu.edutec.fotos.model.TblPhoto;
import sv.edu.edutec.fotos.model.TblUser;
import sv.edu.edutec.fotos.service.PhotoService;

@Component
@Controller
public class CommentServlet {
	
	@Autowired
	PhotoService photoService;
	
	@RequestMapping(value = "addComment", method = RequestMethod.GET)
	public String addComments(Map<String, Object> map,@RequestParam("photoId") String id){
		TblPhoto tblPhoto = photoService.findPhoto(Integer.valueOf(id));
		TblComment tblComment = new TblComment();
		tblComment.setTblPhoto(tblPhoto);
		
		Authentication a = SecurityContextHolder.getContext().getAuthentication();
		User u = (User)a.getPrincipal();
		System.out.println(u.getUsername());
		List<TblUser> userList =photoService.listUsers("from TblUser where username='" + u.getUsername() + "'");
		tblComment.setTblUser(userList.get(0));
		map.put("comment", tblComment);
		return "addComment";
	}
	
	@RequestMapping(value = "saveComment", method = RequestMethod.POST)
	public String saveComments(@ModelAttribute("comment") TblComment tblComment, BindingResult result ){
		if(!result.hasErrors())
		{
			photoService.addComment(tblComment);
			return "redirect:/showPhoto";
		}
		
		return "redirect:/index";
	}

}
